package utils;

import main.WoTCWBot;
import config.Constants;
import de.stefan1200.jts3serverquery.JTS3ServerQuery;

public class TS3 
{
	private JTS3ServerQuery query = new JTS3ServerQuery();
	WoTCWBot m;
	
	public TS3(WoTCWBot m)
	{
		this.m=m;
	}
	
	public String getLastError()
	{
		return query.getLastError();
	}
	
	public void shutdown()
	{
		WoTCWBot.LOGGER.info("Shutting down TS3Connection");
		query.closeTS3Connection();
	}
	
	
	public boolean init() 
	{

		WoTCWBot.LOGGER.info("connecting to ts3");
		if (!query.connectTS3Query(Constants.TS3_IP, Constants.TS3_QUERY_PORT))
		{
			WoTCWBot.LOGGER.fatal(query.getLastError());
			WoTCWBot.LOGGER.fatal("cannot connect to ts3 "+Constants.TS3_IP+" on port "+Constants.TS3_QUERY_PORT);
		}
		else
		{
			WoTCWBot.LOGGER.debug("logging in");
			
			query.loginTS3(Constants.TS3_QUERY_USERNAME,Constants.TS3_QUERY_PASSWORD); 
			

		
			// Select virtual Server
			WoTCWBot.LOGGER.debug("selecting virtual server");
			if (!query.selectVirtualServer(Constants.TS3_PORT,true))
			{
				WoTCWBot.LOGGER.fatal(query.getLastError());
				WoTCWBot.LOGGER.fatal("cannot select virtual server: "+query.getLastError());
			}
			else
			{
				Constants.TS3_SERVER_ID = query.getCurrentQueryClientServerID();
				WoTCWBot.LOGGER.info("ts3 virtual server id="+Constants.TS3_SERVER_ID);
				WoTCWBot.LOGGER.debug("setting display name");
				if(!query.setDisplayName(Constants.TS3_DISPLAY_NAME))
				{
					WoTCWBot.LOGGER.fatal(query.getLastError());
					WoTCWBot.LOGGER.fatal("cannot change displayname: "+query.getLastError());
				}
				else
				{
					WoTCWBot.LOGGER.debug("setting TeamspeakActionListener and register EVENT_MODE_SERVER");
					query.setTeamspeakActionListener(new WoTCWBotTeamspeakActionListener(m));
					query.addEventNotify(JTS3ServerQuery.EVENT_MODE_SERVER, 0);
					WoTCWBot.LOGGER.debug("TS3 initialized successfully");
					return true;
				}
			}
		}
		WoTCWBot.LOGGER.fatal("failed to init TS3");
		return false;
	}
	
	
	
	public void keepalive()
	{
		WoTCWBot.LOGGER.trace("keepalive");
		query.getList(JTS3ServerQuery.LISTMODE_CLIENTLIST);
		String le = query.getLastError();
		if(le!=null)
		{
			WoTCWBot.LOGGER.error("keepalive error: "+le);
			query.closeTS3Connection();
			init();
		}
	}
	public boolean send(String text)
	{
		if(!query.sendTextMessage(Constants.TS3_SERVER_ID,JTS3ServerQuery.TEXTMESSAGE_TARGET_VIRTUALSERVER,text))
		{
			WoTCWBot.LOGGER.error("could not send message (first try) "+query.getLastError());
			if(init())
			{
				if(!query.sendTextMessage(Constants.TS3_PORT,JTS3ServerQuery.TEXTMESSAGE_TARGET_VIRTUALSERVER,text))
				{
					WoTCWBot.LOGGER.fatal("could not send message (second try) "+query.getLastError());
				}
				else
				{
					return true;
				}
			}
		}
		else
		{
			return true;
		}
		return false;
	}
}
